package com.ciwong.epaper.modules.epaper.ui;

import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.bookstore.bean.PubLishClassBean;
import com.ciwong.epaper.modules.bookstore.bean.PublishStudentBean;
import com.ciwong.epaper.modules.bookstore.bean.StudentGroupBean;
import com.ciwong.epaper.modules.clazz.bean.StudentBean;
import com.ciwong.epaper.modules.epaper.adapter.ChooseGroupAdapter;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 发布作业选择分组页面
 */
public class ChooseGroupActivity extends BaseActivity {

    private ExpandableListView publish_choose_group_list;

    private String clientId;

    private int classId;

    private List<StudentBean> studentBeans;

    private ChooseGroupAdapter chooseGroupAdapter;

    private List<StudentGroupBean> studentBeanLists;

    private ImageView publish_work_go_back;

    private int checked;

    private TextView check_stu_count;

    private CheckBox select_all_check;

    private TextView publish_work_title;

    private String className;

    private RelativeLayout choose_group_confirm_lay;

    private PubLishClassBean pubLishClassBean = new PubLishClassBean();
    //是否有vip分组
    private boolean hasVipGroup = false;

    /**
     * 人员总数
     */
    private int countAll;

    private int checkCountAll = 0;

    @Override
    protected int setView() {
        return R.layout.activity_publish_choose_group;
    }

    @Override
    protected void findViews() {
        publish_choose_group_list = (ExpandableListView) findViewById(R.id.publish_choose_group_list);
        publish_work_go_back = (ImageView) findViewById(R.id.publish_work_go_back);
        check_stu_count = (TextView) findViewById(R.id.check_stu_count);
        select_all_check = (CheckBox) findViewById(R.id.select_all_check);
        publish_work_title = (TextView) findViewById(R.id.publish_work_title);
        choose_group_confirm_lay = (RelativeLayout) findViewById(R.id.choose_group_confirm_lay);
        publish_work_go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        publish_choose_group_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return false;
            }
        });

        choose_group_confirm_lay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        select_all_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!compoundButton.isPressed()) {
                    return;
                }
                if (b) {
                    select_all_check.setChecked(true);
                    select_all_check.setSelected(true);
                    for (int i = 0; i < studentBeanLists.size(); i++) {
                        int listSize = studentBeanLists.get(i).getList().size();
                        studentBeanLists.get(i).setCheckCount(listSize);
                        for (int a = 0; a < listSize; a++) {
                            studentBeanLists.get(i).getList().get(a).setCheckStatus(1);
                        }
                    }
                    setCheckCountAndCheckStatus(studentBeanLists);
                    chooseGroupAdapter.notifyDataSetChanged();
                } else {
                    select_all_check.setChecked(false);
                    select_all_check.setSelected(true);
                    for (int i = 0; i < studentBeanLists.size(); i++) {
                        studentBeanLists.get(i).setCheckCount(0);
                        for (int a = 0; a < studentBeanLists.get(i).getList().size(); a++) {
                            studentBeanLists.get(i).getList().get(a).setCheckStatus(2);
                        }
                    }
                    setCheckCountAndCheckStatus(studentBeanLists);
                    chooseGroupAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void init() {
        hideTitleBar();
        Intent intent = getIntent();
        BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
        if (verifyInfo != null) {
            clientId = verifyInfo.getClientId();
        }
        classId = intent.getIntExtra(IntentFlag.INTENT_FLAG_CLASS_ID, 0);
        checked = intent.getIntExtra(IntentFlag.INTENT_FLAG_CHECKID, 0);
        className = intent.getStringExtra(IntentFlag.INTENT_FLAG_CLASS_NAME);
        studentBeanLists =(List<StudentGroupBean>) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_STUDENT_LIST);
        publish_work_title.setText(className);
        chooseGroupAdapter = new ChooseGroupAdapter(studentBeanLists, ChooseGroupActivity.this);
        publish_choose_group_list.setAdapter(chooseGroupAdapter);
    }

    /**
     * 设置选中数量及选中状态
     *
     * @param studentGroupBeans
     */
    public void setCheckCountAndCheckStatus(List<StudentGroupBean> studentGroupBeans) {
        checkCountAll = 0;
        if (hasVipGroup){
            for (int i = 0; i < studentGroupBeans.size()-1; i++) {
                checkCountAll = checkCountAll + studentGroupBeans.get(i).getCheckCount();
            }
        }else {
            for (int i = 0; i < studentGroupBeans.size(); i++) {
                checkCountAll = checkCountAll + studentGroupBeans.get(i).getCheckCount();
            }
        }

        if (checkCountAll == countAll) {
            select_all_check.setChecked(true);
            select_all_check.setSelected(true);
        } else if (0 == checkCountAll) {
            select_all_check.setChecked(false);
            select_all_check.setSelected(true);
        } else {
            select_all_check.setChecked(true);
            select_all_check.setSelected(false);
        }
        check_stu_count.setText("共计：" + checkCountAll + "人");
    }

    @Override
    protected void loadData() {
        showCricleProgress();
        if (null == studentBeanLists || studentBeanLists.size() == 0 || studentBeanLists.get(0).getClassId() != classId){
            getMembers(classId, clientId, 1, 1, 1);
        }else {
            hideCricleProgress();
            for (int i = 0; i < studentBeanLists.size(); i++) {
                List<StudentBean> list = studentBeanLists.get(i).getList();
                countAll = countAll + list.size();
            }
            //获取vip分组
            getVipGroup();
            //设置选中状态
            setCheckCountAndCheckStatus(studentBeanLists);
            chooseGroupAdapter.setNewData(studentBeanLists);
            for (int i = 0; i < chooseGroupAdapter.getGroupCount(); i++) {
                publish_choose_group_list.expandGroup(i);
            }
        }
    }

    /**
     * 获取班级成员
     * @param classId
     * @param clientId
     * @param getIntegral
     * @param getVip
     * @param role
     */
    public void getMembers(final int classId, String clientId, int getIntegral, int getVip, int role) {

        EpaperDao.getInstance().getmembers(classId, clientId, getIntegral, getVip, role, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void failed(Object data) {
                if (data instanceof TimeoutError) {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    hideCricleProgress();
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data && data instanceof ArrayList) {
                    studentBeans = (List<StudentBean>) data;
                    countAll = studentBeans.size();
                    studentBeanLists = new ArrayList<>();
                    //获取vip分组
                    StudentGroupBean stuVip = new StudentGroupBean();
                    List<StudentBean> stuVipList = new ArrayList<>();
                    Map<Integer, String> map = new HashMap<>();
                    for (StudentBean stu : studentBeans) {
                        map.put(stu.getTeamId(), stu.getTeamName());
                        if (stu.getIsVip() == 1){
                            hasVipGroup = true;
                            stu.setCheckStatus(checked);
                            stuVipList.add(stu);
                        }
                    }
                    stuVip.setList(stuVipList);
                    stuVip.setTeamName("vip");
                    stuVip.setClassId(classId);
                    if (1 == checked) {
                        stuVip.setCheckCount(stuVipList.size());
                    } else {
                        stuVip.setCheckCount(0);
                    }
                    Set<Integer> integers = map.keySet();
                    for (Integer integer : integers) {
                        List<StudentBean> stuList = new ArrayList<>();
                        StudentGroupBean studentGroupBean = new StudentGroupBean();
                        for (int i = 0; i < studentBeans.size(); i++) {
                            if (1==checked){
                                studentBeans.get(i).setCheckStatus(1);
                            }else {
                                studentBeans.get(i).setCheckStatus(2);
                            }
                            if (studentBeans.get(i).getTeamId() == integer) {
                                stuList.add(studentBeans.get(i));
                            }
                        }
                        studentGroupBean.setList(stuList);
                        studentGroupBean.setClassId(classId);
                        if (stuList.size() > 0){
                            studentGroupBean.setTeamName(stuList.get(0).getTeamName());
                        }
                        if (1 == checked) {
                            studentGroupBean.setCheckCount(stuList.size());
                        } else {
                            studentGroupBean.setCheckCount(0);
                        }
                        studentBeanLists.add(studentGroupBean);
                    }
                    if (null != stuVip.getList() && stuVip.getList().size()>0){
                        studentBeanLists.add(stuVip);
                    }
                    //设置选中状态
                    setCheckCountAndCheckStatus(studentBeanLists);
                    chooseGroupAdapter.setNewData(studentBeanLists);
                    for (int i = 0; i < chooseGroupAdapter.getGroupCount(); i++) {
                        publish_choose_group_list.expandGroup(i);
                    }
                }

            }
        });

    }

    /**
     * 获取vip分组
     */
    public void getVipGroup(){
        //获取vip分组
        StudentGroupBean stuVip = new StudentGroupBean();
        List<StudentBean> stuVipList = new ArrayList<>();
        int checkCount = 0;
        for (int i = 0; i < studentBeanLists.size(); i++) {
            List<StudentBean> list = studentBeanLists.get(i).getList();
            for (int a = 0; a < list.size(); a++) {
                if (list.get(a).getIsVip() == 1){
                    hasVipGroup = true;
                    stuVipList.add(list.get(a));
                    if (list.get(a).getCheckStatus() == 1){
                        checkCount++;
                    }

                }
            }
        }
        stuVip.setList(stuVipList);
        stuVip.setTeamName("vip");
        stuVip.setClassId(classId);
        stuVip.setCheckCount(checkCount);
        if (null != stuVip.getList() && stuVip.getList().size()>0){
            studentBeanLists.add(stuVip);
        }
    }


    @Override
    public void finish() {
        // setLocalData();
        setChooseResult();
        super.finish();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            setChooseResult();
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void setChooseResult() {
        if (0 != checkCountAll){
            pubLishClassBean.setClassId(classId+"");
            pubLishClassBean.setClassName(className);
            pubLishClassBean.setSelectStudentLength(checkCountAll);
            pubLishClassBean.setStudentCount(countAll);
            pubLishClassBean.setPublishType(0);
            List<PublishStudentBean> publishStudentBeanList = new ArrayList<>();

            if (hasVipGroup){
                //如果有vip分组 统计人数时则不计算vip分组
                if (studentBeanLists.get(studentBeanLists.size() - 1).getTeamName().equals("vip")){
                    studentBeanLists.remove(studentBeanLists.size() - 1);
                }
                for (int i = 0; i < studentBeanLists.size(); i++) {
                    StudentGroupBean studentGroupBean = studentBeanLists.get(i);
                    List<StudentBean> studentBeanList = studentGroupBean.getList();
                    //根据选择人数判断是否全选 只有全选才需要组名
                    if (studentGroupBean.getCheckCount() == studentBeanList.size()){
                        for (int i1 = 0; i1 < studentBeanList.size(); i1++) {
                            StudentBean studentBean = studentBeanList.get(i1);
                            //根据checkstatus 选中状态 将选中的学生放入 布置作业对象集合中
                            if (studentBean.getCheckStatus() == 1){
                                PublishStudentBean publishStudentBean = new PublishStudentBean();
                                publishStudentBean.setGroupName(studentBean.getTeamName());
                                publishStudentBean.setUserId(studentBean.getUserId());
                                publishStudentBean.setUserName(studentBean.getUserName());
                                publishStudentBeanList.add(publishStudentBean);
                            }
                        }
                    }else {
                        for (int i1 = 0; i1 < studentBeanList.size(); i1++) {
                            StudentBean studentBean = studentBeanList.get(i1);
                            //根据checkstatus 选中状态 将选中的学生放入 布置作业对象集合中
                            if (studentBean.getCheckStatus() == 1){
                                PublishStudentBean publishStudentBean = new PublishStudentBean();
                                publishStudentBean.setGroupName("");
                                publishStudentBean.setUserId(studentBean.getUserId());
                                publishStudentBean.setUserName(studentBean.getUserName());
                                publishStudentBeanList.add(publishStudentBean);
                            }
                        }
                    }
                }
            }else {
                for (int i = 0; i < studentBeanLists.size(); i++) {
                    StudentGroupBean studentGroupBean = studentBeanLists.get(i);
                    List<StudentBean> studentBeanList = studentGroupBean.getList();
                    //根据选择人数判断是否全选 只有全选才需要组名
                    if (studentGroupBean.getCheckCount() == studentBeanList.size()){
                        for (int i1 = 0; i1 < studentBeanList.size(); i1++) {
                            StudentBean studentBean = studentBeanList.get(i1);
                            //根据checkstatus 选中状态 将选中的学生放入 布置作业对象集合中
                            if (studentBean.getCheckStatus() == 1){
                                PublishStudentBean publishStudentBean = new PublishStudentBean();
                                publishStudentBean.setGroupName(studentBean.getTeamName());
                                publishStudentBean.setUserId(studentBean.getUserId());
                                publishStudentBean.setUserName(studentBean.getUserName());
                                publishStudentBeanList.add(publishStudentBean);
                            }
                        }
                    }else {
                        for (int i1 = 0; i1 < studentBeanList.size(); i1++) {
                            StudentBean studentBean = studentBeanList.get(i1);
                            //根据checkstatus 选中状态 将选中的学生放入 布置作业对象集合中
                            if (studentBean.getCheckStatus() == 1){
                                PublishStudentBean publishStudentBean = new PublishStudentBean();
                                publishStudentBean.setGroupName("");
                                publishStudentBean.setUserId(studentBean.getUserId());
                                publishStudentBean.setUserName(studentBean.getUserName());
                                publishStudentBeanList.add(publishStudentBean);
                            }
                        }
                    }
                }
            }
            pubLishClassBean.setUserList(publishStudentBeanList);
        }else {
            pubLishClassBean.setClassId(classId+"");
            pubLishClassBean.setClassName(className);
            pubLishClassBean.setSelectStudentLength(checkCountAll);
            pubLishClassBean.setStudentCount(countAll);
            pubLishClassBean.setPublishType(0);

            if (hasVipGroup) {
                //如果有vip分组 统计人数时则不计算vip分组
                if (studentBeanLists.get(studentBeanLists.size() - 1).getTeamName().equals("vip")){
                    studentBeanLists.remove(studentBeanLists.size() - 1);
                }
            }
        }
        Intent intent = new Intent();
        intent.putExtra(IntentFlag.INTENT_FLAG_CHOOES_STU, (Serializable) pubLishClassBean);
        intent.putExtra(IntentFlag.INTENT_FLAG_STUDENT_LIST,(Serializable) studentBeanLists);
        setResult(RESULT_OK, intent);
    }
}
